// react-native版的DeviceBindScreen
import React, {useEffect} from 'react';
import {View, Text, Dimensions, StyleSheet, ToastAndroid} from 'react-native';
import {TextInput, TouchableHighlight} from 'react-native-gesture-handler';
import Row from '../components/Row';
import {Select} from 'teaset';
import LinearGradient from 'react-native-linear-gradient';
import DeviceInfo from 'react-native-device-info';
import {get, post} from '../http/http';
import Ionicons from 'react-native-vector-icons/Ionicons';
import ModalViewUtil from '../components/ModalViewUtil';
import LoginView from '../views/LoginView';
import config from '../config/config';
import {useResponsive} from 'react-native-responsive-hook';

const WIN_WIDTH = Dimensions.get('window').width;
export default function DeviceBindScreen(props) {
  const [elecCards, setElecCards] = React.useState([]);
  const [elecCard, setElecCard] = React.useState(null);
  const [exist, setExist] = React.useState(false);
  const [devicePosition, setDevicePosition] = React.useState(null);
  const {wp, hp, rem} = useResponsive();
  const deviceIp = DeviceInfo.getIpAddressSync();
  const deviceId = config.DEVICE_ID;

  useEffect(() => {
    const loadData = async () => {
      const {data} = await get(
        '/assets/materialCabinet/api/getUnBindMaterialCabinetList',
        {page: 1, limit: 999},
      );
      const card = data.data.find(v => v.deviceId === deviceId);
      console.log('data:', data);
      setElecCards(data.data);
      console.log('-->', data.data);
      setElecCard(card);
      setExist(!!card);
    };
    loadData().catch(error => {
      if (error.message === 'token参数为空') {
        ModalViewUtil.showFromCenter(
          <LoginView
            userType={2}
            loginCancel={() => {
              ModalViewUtil.dismissBottomView();
            }}
            loginComplete={() => {
              ModalViewUtil.dismissView();
              loadData();
            }}
          />,
          true,
        );
      }
      console.log('--->', error);
    });
  }, []);

  const bindDevice = async text => {
    try {
      let uniqueId = config.DEVICE_ID; //DeviceInfo.getUniqueId();
      await post('/assets/materialCabinet/api/bindingMaterialCabinet', {
        deviceId: uniqueId,
        materialCabinetId: elecCard.materialCabinetId,
      });
      ToastAndroid.show('绑定成功', ToastAndroid.SHORT);
      props.navigation.goBack();
    } catch (e) {
      ToastAndroid.show(e.message, ToastAndroid.SHORT);
    }
  };

  const styles = StyleSheet.create({
    selectStyle: {
      width: WIN_WIDTH / 2,
      borderColor: '#46BE88',
      borderWidth: 3,
      backgroundColor: '#112E32',
      borderRadius: 8,
      height: hp(5),
    },
    selectValueStyle: {
      color: 'white',
      fontSize: 48 / 2,
    },
    linearGradient: {
      paddingLeft: 30,
      paddingRight: 30,
      borderRadius: hp(2.5),
      height: hp(5),
      width: wp(50),
    },
    buttonText: {
      fontSize: 36 / 2,
      textAlign: 'center',
      margin: 20,
      color: '#ffffff',
      backgroundColor: 'transparent',
    },
    inputStyle: {
      width: WIN_WIDTH / 2,
      borderColor: '#46BE88',
      paddingHorizontal: 15,
      borderWidth: 3,
      backgroundColor: '#112E32',
      borderRadius: 8,
      color: 'white',
      fontSize: 20,
    },
  });

  const getItemText = (item, index) => {
    console.log('item:', item);
    return (
      <View
        style={{
          width: WIN_WIDTH / 2 - 50,
          backgroundColor:
            elecCard && elecCard === item ? '#46BE88' : 'transparent',
          // paddingVertical: (10),
          borderRadius: 16,
          // marginRight: 60,
          height: hp(3),
        }}>
        <Text
          style={{
            color: elecCard && elecCard === item ? 'white' : '#333',
            fontSize: 48 / 2,
            lineHeight: hp(3),
          }}>
          {item.merchantName}-{item.materialCabinetName}
        </Text>
      </View>
    );
  };

  return (
    <View
      style={{
        width: '100%',
        alignItems: 'center',
        backgroundColor: '#121212',
        height: '100%',
        borderRadius: 10,
      }}>
      <Text
        style={{
          fontSize: 30,
          fontWeight: 'bold',
          color: 'white',
          marginTop: 50,
        }}>
        设备注册
      </Text>
      <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
        <Row
          style={{
            alignItems: 'center',
            justifyContent: 'center',
            marginTop: 40,
          }}>
          <Text
            style={{
              fontSize: 24,
              color: '#63DA9B',
              width: 130,
              marginRight: 10,
            }}>
            设备ID:
          </Text>
          <TextInput
            editable={false}
            style={styles.inputStyle}
            value={deviceId}
          />
        </Row>
        <Row style={{justifyContent: 'center', marginTop: 40}}>
          <Text
            style={{
              fontSize: 48 / 2,
              color: '#63DA9B',
              width: 130,
              marginRight: 10,
            }}>
            所属物料柜:
          </Text>
          <Select
            iconTintColor={'#44BC86'}
            valueStyle={styles.selectValueStyle}
            style={styles.selectStyle}
            onSelected={(item, index) => {
              setElecCard(elecCards[index]);
              setDevicePosition(elecCards[index].devicePosition);
            }}
            value={elecCard}
            popoverStyle={{width: wp(50), maxWidth: wp(50)}}
            pickerType={'popover'}
            getItemValue={(item, index) => item}
            items={elecCards}
            getItemText={getItemText}
            icon={
              <View style={{width: 40, marginLeft: 40}}>
                <Ionicons name={'chevron-down'} size={40} color={'#44BC86'} />
              </View>
            }
          />
        </Row>
        <View style={{marginTop: 40, marginBottom: 40}}>
          <TouchableHighlight onPress={bindDevice}>
            <LinearGradient
              colors={['#30CF9C', '#1AA6F6']}
              start={{x: 0, y: 0}}
              end={{x: 1, y: 0}}
              style={styles.linearGradient}>
              <Text style={styles.buttonText}>{exist ? '解绑' : '绑定'}</Text>
            </LinearGradient>
          </TouchableHighlight>
        </View>
      </View>
    </View>
  );
}
